package view;

import com.toedter.calendar.JDateChooser;
import model.Student;
import model.Class;
import service.StudentService;
import service.ClassService;
import service.DepartmentService;
import service.MajorService;
import model.Department;
import model.Major;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.io.File;
import view.common.ButtonEditor;
import view.common.ButtonRenderer;

public class StudentManagementPanel extends JPanel {
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    
    private StudentService studentService;
    private ClassService classService;
    private DepartmentService departmentService;
    private MajorService majorService;
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JComboBox<String> classFilterComboBox;
    private Map<String, Integer> classIdMap = new HashMap<>();
    private JTextField studentNoField;
    private JTextField nameField;
    private JTextField phoneField;
    private JTextField emailField;
    private String selectedDeptCode;
    private String selectedMajorCode;
    private int selectedClassId;
    
    public StudentManagementPanel() {
        this.studentService = new StudentService();
        this.classService = new ClassService();
        this.departmentService = new DepartmentService();
        this.majorService = new MajorService();
        initComponents();
        loadStudentData();
    }
    
    private void initComponents() {
        setLayout(new BorderLayout());
        
        // 顶部工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        // 班级过滤
        toolBar.add(new JLabel("班级："));
        classFilterComboBox = new JComboBox<>();
        loadClasses();
        classFilterComboBox.addActionListener(e -> loadStudentData());
        toolBar.add(classFilterComboBox);
        
        // 添加学生按钮
        JButton addButton = new JButton("添加学生");
        addButton.addActionListener(e -> showAddStudentDialog());
        toolBar.add(addButton);
        
        // 批量导入按钮
        JButton importButton = new JButton("批量导入");
        importButton.addActionListener(e -> importStudents());
        toolBar.add(importButton);
        
        add(toolBar, BorderLayout.NORTH);
        
        // 学生表格
        String[] columnNames = {
            "学号", "姓名", "性别", "系部", "专业", "班级", "身份证号", "联系电话", 
            "家庭住址", "入学年份", "状态", "操作"
        };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == columnNames.length - 1;  // 只���操作列可编辑
            }
        };
        
        studentTable = new JTable(tableModel);
        studentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        studentTable.setFont(CONTENT_FONT);
        studentTable.getTableHeader().setFont(TITLE_FONT);
        studentTable.setRowHeight(30);  // 增加行高
        
        // 设置操作列
        TableColumn operationColumn = studentTable.getColumnModel().getColumn(11);
        operationColumn.setCellRenderer(new ButtonRenderer());
        operationColumn.setCellEditor(new ButtonEditor(e -> {
            int row = studentTable.getSelectedRow();
            if (row != -1) {
                String studentNo = (String) tableModel.getValueAt(row, 0);
                if ("编辑".equals(e.getActionCommand())) {
                    editStudent(studentNo);
                } else if ("删除".equals(e.getActionCommand())) {
                    deleteStudent(studentNo);
                }
            }
        }));
        
        // 设置列宽
        int[] columnWidths = {100, 80, 50, 100, 100, 100, 150, 100, 150, 80, 60, 150};
        for (int i = 0; i < columnWidths.length; i++) {
            studentTable.getColumnModel().getColumn(i).setPreferredWidth(columnWidths[i]);
        }
        
        add(new JScrollPane(studentTable), BorderLayout.CENTER);
    }
    
    private void loadClasses() {
        classFilterComboBox.addItem("全部");
        List<Class> classes = classService.getAllClasses();
        for (Class cls : classes) {
            classFilterComboBox.addItem(cls.getClassName());
            classIdMap.put(cls.getClassName(), cls.getId());
        }
    }
    
    private void loadStudentData() {
        tableModel.setRowCount(0);
        List<Student> students = studentService.getAllStudents();
        for (Student student : students) {
            Object[] rowData = {
                student.getStudentNo(),
                student.getName(),
                student.getGender(),
                student.getDepartmentName(),
                student.getMajorName(),
                student.getClassName(),
                student.getIdCard(),
                student.getPhone(),
                student.getHomeAddress(),
                student.getEnrollmentYear(),
                student.getStatus(),
                "操作"
            };
            tableModel.addRow(rowData);
        }
    }
    
    private void importStudents() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter(
            "Excel Files", "xlsx"));
        
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            // TODO: 实现Excel导入逻辑
        }
    }
    
    private void showAddStudentDialog() {
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "添加学生", true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 添加系部、专业、班级选择
        JComboBox<String> deptCombo = new JComboBox<>();
        JComboBox<String> majorCombo = new JComboBox<>();
        JComboBox<String> classCombo = new JComboBox<>();
        
        // 加载系部数据
        List<Department> departments = departmentService.getAllDepartments();
        for (Department dept : departments) {
            deptCombo.addItem(dept.getDeptName() + " (" + dept.getDeptCode() + ")");
        }
        
        // 系选择事件
        deptCombo.addActionListener(e -> {
            majorCombo.removeAllItems();
            String selected = (String) deptCombo.getSelectedItem();
            if (selected != null) {
                selectedDeptCode = selected.substring(
                    selected.lastIndexOf("(") + 1, 
                    selected.lastIndexOf(")")
                );
                // 加载该系部的专业
                List<Major> majors = departmentService.getDepartmentMajors(selectedDeptCode);
                for (Major major : majors) {
                    majorCombo.addItem(major.getMajorName() + " (" + major.getMajorCode() + ")");
                }
            }
        });
        
        // 专业选择事件
        majorCombo.addActionListener(e -> {
            classCombo.removeAllItems();
            String selected = (String) majorCombo.getSelectedItem();
            if (selected != null) {
                selectedMajorCode = selected.substring(
                    selected.lastIndexOf("(") + 1, 
                    selected.lastIndexOf(")")
                );
                // 加载该专业的班级
                List<Class> classes = classService.getClassesByMajor(selectedMajorCode);
                for (Class cls : classes) {
                    classCombo.addItem(cls.getClassName());
                }
            }
        });
        
        // 班级选择事件
        classCombo.addActionListener(e -> {
            String selected = (String) classCombo.getSelectedItem();
            if (selected != null) {
                selectedClassId = classIdMap.get(selected);
            }
        });
        
        // 设置组件大小和字体
        Dimension fieldSize = new Dimension(250, 30);
        deptCombo.setPreferredSize(fieldSize);
        majorCombo.setPreferredSize(fieldSize);
        classCombo.setPreferredSize(fieldSize);
        
        deptCombo.setFont(CONTENT_FONT);
        majorCombo.setFont(CONTENT_FONT);
        classCombo.setFont(CONTENT_FONT);
        
        // 添加选择组件到表单
        addFormField(formPanel, "系部：", deptCombo, gbc, 0);
        addFormField(formPanel, "专业：", majorCombo, gbc, 1);
        addFormField(formPanel, "班级：", classCombo, gbc, 2);
        
        // 创建输入组件
        JTextField nameField = new JTextField(20);
        JComboBox<String> genderCombo = new JComboBox<>(new String[]{"男", "女"});
        JTextField phoneField = new JTextField(20);
        JTextField emailField = new JTextField(20);
        JTextField addressField = new JTextField(20);
        JTextField idCardField = new JTextField(20);
        
        // 创建日期选择器
        JDateChooser birthDateChooser = new JDateChooser();
        birthDateChooser.setDateFormatString("yyyy-MM-dd");
        
        // 使用相同的 fieldSize 设置其他组件大小
        nameField.setPreferredSize(fieldSize);
        genderCombo.setPreferredSize(fieldSize);
        phoneField.setPreferredSize(fieldSize);
        emailField.setPreferredSize(fieldSize);
        addressField.setPreferredSize(fieldSize);
        idCardField.setPreferredSize(fieldSize);
        birthDateChooser.setPreferredSize(fieldSize);
        
        // 设置字体
        nameField.setFont(CONTENT_FONT);
        genderCombo.setFont(CONTENT_FONT);
        phoneField.setFont(CONTENT_FONT);
        emailField.setFont(CONTENT_FONT);
        addressField.setFont(CONTENT_FONT);
        idCardField.setFont(CONTENT_FONT);
        birthDateChooser.setFont(CONTENT_FONT);
        
        // 添加到表单
        addFormField(formPanel, "姓名：", nameField, gbc, 3);
        addFormField(formPanel, "身份证：", idCardField, gbc, 4);
        addFormField(formPanel, "性别：", genderCombo, gbc, 5);
        addFormField(formPanel, "出生日期：", birthDateChooser, gbc, 6);
        addFormField(formPanel, "电话：", phoneField, gbc, 7);
        addFormField(formPanel, "邮箱：", emailField, gbc, 8);
        addFormField(formPanel, "家庭住址：", addressField, gbc, 9);
        
        dialog.add(formPanel, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        // 设置按钮大小和字体
        Dimension buttonSize = new Dimension(90, 32);
        saveButton.setPreferredSize(buttonSize);
        cancelButton.setPreferredSize(buttonSize);
        saveButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);
        
        // 保存按钮事件
        saveButton.addActionListener(e -> {
            String idCard = idCardField.getText().trim();
            if (!validateIdCard(idCard)) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的身份证号码！");
                return;
            }
            
            Student student = new Student();
            student.setName(nameField.getText().trim());
            student.setGender((String) genderCombo.getSelectedItem());
            student.setPhone(phoneField.getText().trim());
            student.setEmail(emailField.getText().trim());
            student.setBirthDate(new java.sql.Date(birthDateChooser.getDate().getTime()));
            student.setHomeAddress(addressField.getText().trim());
            student.setIdCard(idCard);
            student.setClassId(selectedClassId);
            student.setEnrollmentYear(Calendar.getInstance().get(Calendar.YEAR));
            student.setStudentNo(generateStudentNo(selectedDeptCode, selectedMajorCode, 
                selectedClassId));
            
            if (studentService.createStudent(student)) {
                dialog.dispose();
                loadStudentData();
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.setSize(450, 500);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void addFormField(JPanel panel, String label, JComponent field, 
            GridBagConstraints gbc, int row) {
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.anchor = GridBagConstraints.EAST;
        JLabel jLabel = new JLabel(label);
        jLabel.setFont(CONTENT_FONT);
        panel.add(jLabel, gbc);
        
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.weightx = 1.0;
        panel.add(field, gbc);
        gbc.weightx = 0.0;
    }
    
    // 生成学号的方法
    private String generateStudentNo(String deptCode, String majorCode, int classId) {
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        
        // 获取当前班级的最大序号
        int maxSeq = studentService.getMaxSequenceNumber(classId);
        int nextSeq = maxSeq + 1;
        
        // 格式化学号
        return String.format("%d%02d%02d%02d%02d",
            year,                           // 入学年份(4位)
            Integer.parseInt(deptCode),     // 系部编号(2位)
            Integer.parseInt(majorCode),    // 专业编号(2位)
            classId % 100,                 // 班级号(2位)
            nextSeq                        // 序号(2位)
        );
    }
    
    private void updateStudentStatus(String studentNo, String status) {
        if (studentService.updateStudentStatus(studentNo, status)) {
            loadStudentData();
        } else {
            JOptionPane.showMessageDialog(this, "更新学生状态失败！");
        }
    }
    
    // ButtonRenderer 类
    class ButtonRenderer extends JPanel implements TableCellRenderer {
        private JButton editButton = new JButton("编辑");
        private JButton deleteButton = new JButton("删除");
        
        public ButtonRenderer() {
            setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
            add(editButton);
            add(deleteButton);
        }
        
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            return this;
        }
    }
    
    // 添加身份证验证方法
    private boolean validateIdCard(String idCard) {
        // 简单的验证规则：18位，最后一位可以是数字或X/x
        if (idCard == null || idCard.isEmpty()) {
            return false;
        }
        String pattern = "^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[0-9Xx]$";
        return idCard.matches(pattern);
    }
    
    // 添加编辑学生方法
    private void editStudent(String studentNo) {
        Student student = studentService.getStudentByStudentNo(studentNo);
        if (student == null) {
            JOptionPane.showMessageDialog(this, "找不到该学生信息！");
            return;
        }
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "编辑学生", true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 添加系部、专业、班级选择
        JComboBox<String> deptCombo = new JComboBox<>();
        JComboBox<String> majorCombo = new JComboBox<>();
        JComboBox<String> classCombo = new JComboBox<>();
        
        // 加载系部数据
        List<Department> departments = departmentService.getAllDepartments();
        for (Department dept : departments) {
            deptCombo.addItem(dept.getDeptName() + " (" + dept.getDeptCode() + ")");
            if (dept.getDeptName().equals(student.getDepartmentName())) {
                deptCombo.setSelectedItem(dept.getDeptName() + " (" + dept.getDeptCode() + ")");
                selectedDeptCode = dept.getDeptCode();
            }
        }
        
        // 系选择事件
        deptCombo.addActionListener(e -> {
            majorCombo.removeAllItems();
            String selected = (String) deptCombo.getSelectedItem();
            if (selected != null) {
                selectedDeptCode = selected.substring(
                    selected.lastIndexOf("(") + 1, 
                    selected.lastIndexOf(")")
                );
                // 加载该系部的专业
                List<Major> majors = departmentService.getDepartmentMajors(selectedDeptCode);
                for (Major major : majors) {
                    majorCombo.addItem(major.getMajorName() + " (" + major.getMajorCode() + ")");
                }
            }
        });
        
        // 加载专业数据
        List<Major> majors = departmentService.getDepartmentMajors(selectedDeptCode);
        for (Major major : majors) {
            majorCombo.addItem(major.getMajorName() + " (" + major.getMajorCode() + ")");
            if (major.getMajorName().equals(student.getMajorName())) {
                majorCombo.setSelectedItem(major.getMajorName() + " (" + major.getMajorCode() + ")");
                selectedMajorCode = major.getMajorCode();
            }
        }
        
        // 专业选择事件
        majorCombo.addActionListener(e -> {
            classCombo.removeAllItems();
            String selected = (String) majorCombo.getSelectedItem();
            if (selected != null) {
                selectedMajorCode = selected.substring(
                    selected.lastIndexOf("(") + 1, 
                    selected.lastIndexOf(")")
                );
                // 加载该专业的班级
                List<Class> classes = classService.getClassesByMajor(selectedMajorCode);
                for (Class cls : classes) {
                    classCombo.addItem(cls.getClassName());
                }
            }
        });
        
        // 加载班级数据
        List<Class> classes = classService.getClassesByMajor(selectedMajorCode);
        for (Class cls : classes) {
            classCombo.addItem(cls.getClassName());
            if (cls.getClassName().equals(student.getClassName())) {
                classCombo.setSelectedItem(cls.getClassName());
                selectedClassId = cls.getId();
            }
        }
        
        // 班级选择事件
        classCombo.addActionListener(e -> {
            String selected = (String) classCombo.getSelectedItem();
            if (selected != null) {
                selectedClassId = classIdMap.get(selected);
            }
        });
        
        // 设置组件大小和字体
        Dimension fieldSize = new Dimension(250, 30);
        deptCombo.setPreferredSize(fieldSize);
        majorCombo.setPreferredSize(fieldSize);
        classCombo.setPreferredSize(fieldSize);
        
        deptCombo.setFont(CONTENT_FONT);
        majorCombo.setFont(CONTENT_FONT);
        classCombo.setFont(CONTENT_FONT);
        
        // 添加选择组件到表单
        addFormField(formPanel, "系部：", deptCombo, gbc, 0);
        addFormField(formPanel, "专业：", majorCombo, gbc, 1);
        addFormField(formPanel, "班级：", classCombo, gbc, 2);
        
        // 学号（不可编辑）
        JTextField studentNoField = new JTextField(student.getStudentNo());
        studentNoField.setEditable(false);
        addFormField(formPanel, "学号：", studentNoField, gbc, 3);
        
        // 其他字段
        JTextField nameField = new JTextField(student.getName());
        JTextField idCardField = new JTextField(student.getIdCard());
        JComboBox<String> genderCombo = new JComboBox<>(new String[]{"男", "女"});
        genderCombo.setSelectedItem(student.getGender());
        JTextField phoneField = new JTextField(student.getPhone());
        JTextField emailField = new JTextField(student.getEmail());
        JTextField addressField = new JTextField(student.getHomeAddress());
        
        // 创建日期选择器
        JDateChooser birthDateChooser = new JDateChooser();
        birthDateChooser.setDate(student.getBirthDate());
        birthDateChooser.setDateFormatString("yyyy-MM-dd");
        
        // 设置组件大小
        nameField.setPreferredSize(fieldSize);
        idCardField.setPreferredSize(fieldSize);
        genderCombo.setPreferredSize(fieldSize);
        phoneField.setPreferredSize(fieldSize);
        emailField.setPreferredSize(fieldSize);
        addressField.setPreferredSize(fieldSize);
        birthDateChooser.setPreferredSize(fieldSize);
        
        // 设置字体
        nameField.setFont(CONTENT_FONT);
        idCardField.setFont(CONTENT_FONT);
        genderCombo.setFont(CONTENT_FONT);
        phoneField.setFont(CONTENT_FONT);
        emailField.setFont(CONTENT_FONT);
        addressField.setFont(CONTENT_FONT);
        birthDateChooser.setFont(CONTENT_FONT);
        
        // 添加到表单
        addFormField(formPanel, "姓名：", nameField, gbc, 4);
        addFormField(formPanel, "身份证：", idCardField, gbc, 5);
        addFormField(formPanel, "性别：", genderCombo, gbc, 6);
        addFormField(formPanel, "出生日期：", birthDateChooser, gbc, 7);
        addFormField(formPanel, "电话：", phoneField, gbc, 8);
        addFormField(formPanel, "邮箱：", emailField, gbc, 9);
        addFormField(formPanel, "家庭住址：", addressField, gbc, 10);
        
        // 状态
        JComboBox<String> statusCombo = new JComboBox<>(new String[]{"在读", "休学", "退学", "毕业"});
        statusCombo.setSelectedItem(student.getStatus());
        statusCombo.setPreferredSize(fieldSize);
        statusCombo.setFont(CONTENT_FONT);
        addFormField(formPanel, "状态：", statusCombo, gbc, 11);
        
        dialog.add(new JScrollPane(formPanel), BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        // 设置按钮样式
        Dimension buttonSize = new Dimension(90, 32);
        saveButton.setPreferredSize(buttonSize);
        cancelButton.setPreferredSize(buttonSize);
        saveButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);
        
        // 保存按钮事件
        saveButton.addActionListener(e -> {
            student.setName(nameField.getText().trim());
            student.setIdCard(idCardField.getText().trim());
            student.setGender((String) genderCombo.getSelectedItem());
            student.setPhone(phoneField.getText().trim());
            student.setEmail(emailField.getText().trim());
            student.setBirthDate(birthDateChooser.getDate());
            student.setHomeAddress(addressField.getText().trim());
            student.setStatus((String) statusCombo.getSelectedItem());
            student.setClassId(selectedClassId);
            
            if (studentService.updateStudent(student)) {
                dialog.dispose();
                loadStudentData();
                JOptionPane.showMessageDialog(this, "更新成功！");
            } else {
                JOptionPane.showMessageDialog(dialog, "更新失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.setSize(450, 650);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    // 添加删除学生方法
    private void deleteStudent(String studentNo) {
        int choice = JOptionPane.showConfirmDialog(
            this,
            "确定要删除该学生吗？\n此操作不可恢复！",
            "删除确认",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.WARNING_MESSAGE
        );
        
        if (choice == JOptionPane.YES_OPTION) {
            if (studentService.deleteStudentByStudentNo(studentNo)) {
                loadStudentData();
                JOptionPane.showMessageDialog(this, "学生删除成功！");
            } else {
                JOptionPane.showMessageDialog(this, "学生删除失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
} 